import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-10-15
 * Time: 15:49
 */
@WebServlet("/studentInfo")
public class StudentInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //假设客户端发来的请求形如/studentInfo?studentId=104&studentId=20
        //就可以通过getParameter方法来拿到这两个id的值
        String queryString=req.getQueryString();
        System.out.println(queryString);
        resp.getWriter().write(queryString);
        String classId=req.getParameter("classId");
        String studentId=req.getParameter("studentId");
        System.out.println("classId: "+classId+"studentId: "+studentId);
        resp.getWriter().write("classId: "+classId+"studentId: "+studentId);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text.html; charset=utf8");
//        //获取到body中的参数
//        //约定body使用application/x-www-from-urlencoded这种格式来传参（本质上是键值对）
//        //这个格式和query string相同!!!只是数据是在body中
//        //针对这种格式获取到值的方式，仍然是getParameter
//        String classId=req.getParameter("classId");
//        String studentId=req.getParameter("studentId");
//        System.out.println("classId: "+classId+"studentId: "+studentId);
//        resp.getWriter().write("classId: "+classId+"studentId: "+studentId);


        //从这里开始来处理JSON格式的请求
        ObjectMapper objectMapper=new ObjectMapper();
        //从请求中的body中进行读取，并解析
        //使用readValue来把json字符串转成java对象
        //第一个参数是一个String或者是一个InputStream
        //第二个参数是转换的结果对应的Java类对象
        Student student = objectMapper.readValue(req.getInputStream(),Student.class);
        System.out.println(student.classId+", "+student.studentId);
        resp.getWriter().write(student.classId+", "+student.studentId);
    }

}
//此处这个类的属性的名字，和json的key要保持一致
//这里的属性是public或者提供public的getter方法
class Student {
   public int classId;
   public String studentId;

}
